package com.shihan._02_juc_concurrent_utils._03_atomic._01_atomicinteger;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description 资源类
 * @Author shihan
 * @Date 2021/8/22 16:10
 * @Version 1.0
 */
public class MyAtomicInteger implements Runnable {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger(AtomicInteger atomicInteger) {
        this.atomicInteger = atomicInteger;
    }

    public Integer add() {
        /**
         * 先 get 获取值，后进行自增操作
         */
        int andIncrement = atomicInteger.getAndIncrement();
        return andIncrement;
    }

    public Integer sub() {
        /**
         * 先 get 获取值，后进行自减操作
         */
        int andDecrement = atomicInteger.getAndDecrement();
        return andDecrement;
    }

    /**
     * 线程内部执行自增十次
     */
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            Integer add = add();
            System.out.println(Thread.currentThread().getName() + "：" + add);
        }
    }
}
